package com.ruibang.glass.purchase.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.Constants;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.DictInfo;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.common.domain.material.MaterialAllManagementInventory;
import com.ruibang.glass.common.domain.material.MaterialManagement;
import com.ruibang.glass.frequencycontrol.annotation.RedissonLock;
import com.ruibang.glass.purchase.constant.PurchaseErrorCode;
import com.ruibang.glass.purchase.constant.PurchaseMenuIdCode;
import com.ruibang.glass.purchase.constant.PurchaseUseMaterialCode;
import com.ruibang.glass.purchase.domain.req.MaterialInventoryItem;
import com.ruibang.glass.purchase.domain.req.PurchaseArrivalReq;
import com.ruibang.glass.purchase.entity.*;
import com.ruibang.glass.purchase.feign.FileApi;
import com.ruibang.glass.purchase.feign.MaterialApi;
import com.ruibang.glass.purchase.feign.PortalApi;
import com.ruibang.glass.purchase.mapper.*;
import com.ruibang.glass.purchase.service.PurchaseArrivalOrdersService;
import com.ruibang.glass.purchase.service.PurchaseArrivalProductService;
import com.ruibang.glass.purchase.service.PurchaseRelatedProductService;
import com.ruibang.glass.purchase.service.PurchaseSpecialApplicationService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.constant.CommonConstant;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.ruibang.glass.common.constants.RedisKey.MATERIAL_IN_WAREHOUSE_NUMBER;
import static com.ruibang.glass.common.constants.RedisKey.MATERIAL_PA_WAREHOUSE_NUMBER;

/**
 * <p>
 * 采购到货单表 服务实现类
 * </p>
 *
 * @author mameng
 * @since 2024-03-28
 */
@Service
public class PurchaseArrivalOrdersServiceImpl extends ServiceImpl<PurchaseArrivalOrdersMapper, PurchaseArrivalOrders> implements PurchaseArrivalOrdersService {


    @Autowired
    private PurchaseArrivalProductService arrivalProductService;

    @Autowired
    private PurchaseReturnsMapper purchaseReturnsMapper;

    @Autowired
    private PurchaseReturnGoodsMapper purchaseReturnGoodsMapper;

    @Autowired
    private FileApi fileApi;

    @Autowired
    private MaterialApi materialApi;

    @Autowired
    private PurchaseSpecialApplicationService purchaseSpecialApplicationService;

    @Autowired
    private PurchaseSpecialApplicationMapper purchaseSpecialApplicationMapper;

    @Autowired
    private RedisSingleService redisService;

    @Autowired
    private PortalApi portalApi;

    @Autowired
    private PurchaseRelatedProductService relatedProductService;

    @Autowired
    private PurchaseOrderDetailsMapper orderDetailsMapper;

    private static final String PURCHASE_IN_NUMBER = "purchase_in_number";

    @Override
    public IPage<PurchaseArrivalOrders> getPage(PurchaseArrivalReq purchaseArrivalReq) {
        LambdaQueryWrapper<PurchaseArrivalOrders> queryWrapper = Wrappers.<PurchaseArrivalOrders>lambdaQuery();
        if (StringUtils.isNotBlank(purchaseArrivalReq.getArrivalConfirmer())) {
            queryWrapper.like(PurchaseArrivalOrders::getArrivalConfirmUser, purchaseArrivalReq.getArrivalConfirmer());
        }
        if (StringUtils.isNotBlank(purchaseArrivalReq.getPurchaseArrivalOrderNumber())) {
            queryWrapper.like(PurchaseArrivalOrders::getPurchaseArrivalOrderNumber, purchaseArrivalReq.getPurchaseArrivalOrderNumber());
        }
        if (StringUtils.isNotBlank(purchaseArrivalReq.getPurchaseOrderNumber())) {
            queryWrapper.like(PurchaseArrivalOrders::getPurchaseOrderNumber, purchaseArrivalReq.getPurchaseOrderNumber());
        }
        if (StringUtils.isNotBlank(purchaseArrivalReq.getInspector())) {
            queryWrapper.like(PurchaseArrivalOrders::getInspector, purchaseArrivalReq.getInspector());
        }
        if (StringUtils.isNotBlank(purchaseArrivalReq.getItemType())) {
            queryWrapper.like(PurchaseArrivalOrders::getItemType, purchaseArrivalReq.getItemType());
        }
        if (StringUtils.isNotBlank(purchaseArrivalReq.getSupplierName())) {
            queryWrapper.like(PurchaseArrivalOrders::getSupplierName, purchaseArrivalReq.getSupplierName());
        }
        Page<PurchaseArrivalOrders> page = baseMapper.selectPage(new Page(purchaseArrivalReq.getPageNo(), purchaseArrivalReq.getPageSize()),
                queryWrapper.orderByDesc(PurchaseArrivalOrders::getCreateTime)
        );

        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            List<PurchaseArrivalProduct> products = arrivalProductService.list(Wrappers.<PurchaseArrivalProduct>lambdaQuery()
                    .in(PurchaseArrivalProduct::getSaleArrivalId, page.getRecords().stream().map(p -> p.getId()).collect(Collectors.toList())));
            if (CollectionUtils.isNotEmpty(products)) {
                Map<String, List<PurchaseArrivalProduct>> productMap = products.stream().collect(Collectors.groupingBy(PurchaseArrivalProduct::getSaleArrivalId));
                for (PurchaseArrivalOrders record : page.getRecords()) {
                    record.setIsResultChanged(CommonConstant.ZERO_STR);
                    List<PurchaseArrivalProduct> arrivalProducts = productMap.get(record.getId());
                    if (CollectionUtils.isNotEmpty(arrivalProducts)) {
                        for (PurchaseArrivalProduct arrivalProduct : arrivalProducts) {
                            if (CommonConstant.ZERO_STR.equals(arrivalProduct.getApproveStatus())
                                    || CommonConstant.FOUR_STR.equals(arrivalProduct.getApproveStatus())) {
                                record.setIsResultChanged(CommonConstant.ONE_STR);
                            }
                        }
                    }
                }
            }
        }

        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkQuality(PurchaseArrivalOrders purchaseArrivalOrder) {
        if (CollectionUtils.isNotEmpty(purchaseArrivalOrder.getPurchaseArrivalProducts())) {
            int totalGoodCount = 0;
            for (PurchaseArrivalProduct product : purchaseArrivalOrder.getPurchaseArrivalProducts()) {
                fileApi.deleteByBusinessId(product.getId());
                if (CollectionUtils.isNotEmpty(product.getFileIds())) {
                    FileBusiness fileBusiness = new FileBusiness();
                    fileBusiness.setFileIds(product.getFileIds());
                    fileBusiness.setBusinessId(product.getId());
                    fileApi.updateBusinessById(fileBusiness);
                }
                product.setSaleArrivalId(purchaseArrivalOrder.getId());
                if (product.getGoodProduct() != null && product.getBadProduct() != null && product.getQuantity() != null) {
                    if (product.getGoodProduct() + product.getBadProduct() != product.getQuantity()) {
                        throw new ServiceException(PurchaseErrorCode.BAD_GOOD_NO_ALL.getCode(), PurchaseErrorCode.BAD_GOOD_NO_ALL.getMsg());
                    }
                    totalGoodCount = totalGoodCount + product.getGoodProduct();
                    if (product.getGoodProduct() > 0) {
                        product.setCheckStatus(Constants.ONE_INT);
                    } else {
                        product.setCheckStatus(Constants.ZERO_INT);
                    }
                }
            }
            arrivalProductService.updateBatchById(purchaseArrivalOrder.getPurchaseArrivalProducts());

            if (totalGoodCount > 0) {
                purchaseArrivalOrder.setCheckStatus(Constants.ONE_INT);
                purchaseArrivalOrder.setStatus(CommonConstant.TWO_STR);
                addMaterial(purchaseArrivalOrder);
            } else {
                purchaseArrivalOrder.setCheckStatus(Constants.ZERO_INT);
            }
            baseMapper.updateById(purchaseArrivalOrder);
        } else {
            throw new ServiceException(PurchaseErrorCode.ARRIVAL_ORDER_ITEM_IS_EMPTY.getCode(), PurchaseErrorCode.ARRIVAL_ORDER_ITEM_IS_EMPTY.getMsg());
        }
    }

    @Override
    public void updateCheckResult(PurchaseArrivalOrders purchaseArrivalOrders) {
        if (CollectionUtils.isEmpty(purchaseArrivalOrders.getPurchaseArrivalProducts())) {
            throw new ServiceException(PurchaseErrorCode.ARRIVAL_ORDER_ITEM_IS_EMPTY.getCode(), PurchaseErrorCode.ARRIVAL_ORDER_ITEM_IS_EMPTY.getMsg());
        }

        for (PurchaseArrivalProduct product : purchaseArrivalOrders.getPurchaseArrivalProducts()) {
            fileApi.deleteByBusinessId(product.getId());
            if (CollectionUtils.isNotEmpty(product.getFileIds())) {
                FileBusiness fileBusiness = new FileBusiness();
                fileBusiness.setFileIds(product.getFileIds());
                fileBusiness.setBusinessId(product.getId());
                fileApi.updateBusinessById(fileBusiness);
            }
        }
        //查看流程是否已发起
        Map<String, List<PurchaseArrivalProduct>> arrivalProductMap = purchaseArrivalOrders.getPurchaseArrivalProducts().stream().collect(Collectors.groupingBy(PurchaseArrivalProduct::getInventoryId));
        List<PurchaseArrivalProduct> arrivalProducts = arrivalProductService.list(Wrappers.<PurchaseArrivalProduct>lambdaQuery().eq(PurchaseArrivalProduct::getSaleArrivalId, purchaseArrivalOrders.getId()));
        Map<String, Integer> oldArrivalProductQuantityMap = arrivalProducts.stream().collect(Collectors.toMap(PurchaseArrivalProduct::getId, PurchaseArrivalProduct::getGoodProduct));
        List<PurchaseArrivalProduct> products = new ArrayList<>();
        List<PurchaseSpecialApplication> purchaseSpecialApplicationList = new ArrayList<>();
        List<PurchaseSpecialApplication> existPurchaseSpecialApplicationList = purchaseSpecialApplicationService.getByArrivalOrderId(purchaseArrivalOrders.getId());
        final Map<String, PurchaseSpecialApplication> existPurchaseSpecialApplicationMap = existPurchaseSpecialApplicationList.stream().collect(Collectors.toMap(PurchaseSpecialApplication::getItemId, e -> e));
        arrivalProductMap.forEach((key, values) -> {
            if (CollectionUtils.isNotEmpty(values)) {
                PurchaseArrivalProduct product = values.get(0);
                if (CommonConstant.ZERO_STR.equals(product.getApproveStatus())) {
                    List<String> orderItemIds = values.stream().map(v -> v.getOrderItemId()).collect(Collectors.toList());
                    List<PurchaseRelatedProduct> relatedProducts = relatedProductService.list(Wrappers.<PurchaseRelatedProduct>lambdaQuery().in(PurchaseRelatedProduct::getId, orderItemIds));
                    Map<String, PurchaseRelatedProduct> relatedProductMap = null;
                    if (CollectionUtils.isNotEmpty(relatedProducts)) {
                        relatedProductMap = relatedProducts.stream().collect(Collectors.toMap(rp -> rp.getId(), rp -> rp, (rp1, rp2) -> rp1));
                    }

                    List<MaterialInventoryItem> inventoryItems = new ArrayList<>();
                    List<PurchaseRelatedProduct> updateRelatedProducts = new ArrayList<>();

                    String detailId = "";
                    //更新商品数据
                    for (PurchaseArrivalProduct value : values) {
                        MaterialInventoryItem inventoryItem = new MaterialInventoryItem();
                        inventoryItem.setItemCode(value.getItemCode());
                        inventoryItem.setGoodProduct(value.getGoodProduct());
                        inventoryItem.setBadProduct(value.getBadProduct());
                        inventoryItem.setInventoryNumber(value.getInventoryNumber());
                        inventoryItems.add(inventoryItem);

                        if (relatedProductMap != null && oldArrivalProductQuantityMap != null) {
                            Integer oldGoodQuantity = oldArrivalProductQuantityMap.get(value.getId());
                            int diff = value.getGoodProduct() - oldGoodQuantity;
                            PurchaseRelatedProduct relatedProduct = relatedProductMap.get(value.getOrderItemId());
                            if (relatedProduct != null) {
                                if (diff > 0) {
                                    if (diff != value.getSurplusQuantity().intValue()) {
                                        detailId = relatedProduct.getDetailId();
                                        int newQuantity = relatedProduct.getQuantity().intValue() - diff;
                                        relatedProduct.setQuantity((double) newQuantity);
                                        updateRelatedProducts.add(relatedProduct);
                                    }
                                } else if (diff < 0) {
                                    detailId = relatedProduct.getDetailId();
                                    int newQuantity = relatedProduct.getQuantity().intValue() + Math.abs(diff);
                                    relatedProduct.setQuantity((double) newQuantity);
                                    updateRelatedProducts.add(relatedProduct);
                                }
                            }

                        }
                        // 判断物品是否有 让步签收
                        if (Constants.TWO_STR.equals(value.getConcessionAcceptance())) {
                            //判断是否生成采购特采跟踪
                            PurchaseSpecialApplication purchaseSpecialApp = existPurchaseSpecialApplicationMap.get(value.getItemId());
                            if (purchaseSpecialApp == null) {
                                Map<Object, Object> userDeptMap = redisService.hmget(RedisKey.USER_GROUP_DEPT_TYPE);
                                PurchaseSpecialApplication purchaseSpecialApplication = new PurchaseSpecialApplication();
                                BeanUtils.copyProperties(value, purchaseSpecialApplication);
                                purchaseSpecialApplication.setProjectName(purchaseArrivalOrders.getProjectNumber());
                                purchaseSpecialApplication.setProjectNumber(purchaseArrivalOrders.getProjectNumber());
                                purchaseSpecialApplication.setInspector(purchaseArrivalOrders.getInspector());
                                purchaseSpecialApplication.setInspectorId(purchaseArrivalOrders.getInspectorId());
                                purchaseSpecialApplication.setArrivalOrderId(purchaseArrivalOrders.getId());
                                if (userDeptMap != null) {
                                    purchaseSpecialApplication.setDepartmentId(userDeptMap.get(purchaseArrivalOrders.getApplicantId()) == null ?
                                            null : userDeptMap.get(purchaseArrivalOrders.getApplicantId()).toString());
                                }
                                purchaseSpecialApplication.setId(null);
                                purchaseSpecialApplicationList.add(purchaseSpecialApplication);
                            }
                        }
                    }


                    if (CollectionUtils.isNotEmpty(updateRelatedProducts)) {
                        relatedProductService.updateBatchById(updateRelatedProducts);
                    }

                    if (CollectionUtils.isNotEmpty(inventoryItems)) {
                        materialApi.updateQualityByNumber(inventoryItems);
                    }

                    if (StringUtils.isNotBlank(detailId)) {
                        orderDetailsMapper.updateOrderStatus(detailId);
                    }
                } else if (CommonConstant.FOUR_STR.equals(product.getApproveStatus())) {
                    //重新发起流程
                    products.addAll(values);
                } else {
                    throw new ServiceException(PurchaseErrorCode.IN_INVENTORY_PROCESS_IS_START.getCode(), PurchaseErrorCode.IN_INVENTORY_PROCESS_IS_START.getMsg());
                }
            }
        });

        //保存特采跟踪记录
        if (CollectionUtils.isNotEmpty(purchaseSpecialApplicationList)) {
            purchaseSpecialApplicationService.saveBatch(purchaseSpecialApplicationList);
        }

        arrivalProductService.updateBatchById(purchaseArrivalOrders.getPurchaseArrivalProducts());

        if (CollectionUtils.isNotEmpty(products)) {
            purchaseArrivalOrders.setPurchaseArrivalProducts(products);
            addMaterial(purchaseArrivalOrders);
        }
    }


    /**
     * 新增入库数据
     *
     * @param purchaseArrivalOrder
     */
    public void addMaterial(PurchaseArrivalOrders purchaseArrivalOrder) {
        if (CollectionUtils.isNotEmpty(purchaseArrivalOrder.getPurchaseArrivalProducts())) {

            List<PurchaseArrivalProduct> purchaseArrivalProducts = purchaseArrivalOrder.getPurchaseArrivalProducts();
            List<String> itemIds = purchaseArrivalProducts.stream().map(p -> p.getItemId()).collect(Collectors.toList());
            ResultBody<List<MaterialManagement>> resultBody = materialApi.getWarehouseByIds(itemIds);
            Map<String, MaterialManagement> itemInfoMap = null;
            if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
                itemInfoMap = resultBody.getData().stream().collect(Collectors.toMap(m -> m.getId(), m1 -> m1, (m1, m2) -> m1));
            }
            List<MaterialInventoryItem> inventoryItems = new ArrayList<>();
            List<String> orderItemIds = purchaseArrivalProducts.stream().map(p -> p.getOrderItemId()).collect(Collectors.toList());

            List<PurchaseRelatedProduct> relatedProducts = relatedProductService.list(Wrappers.<PurchaseRelatedProduct>lambdaQuery().in(PurchaseRelatedProduct::getId, orderItemIds));
            Map<String, PurchaseRelatedProduct> relatedProductMap = null;
            if (CollectionUtils.isNotEmpty(relatedProducts)) {
                relatedProductMap = relatedProducts.stream().collect(Collectors.toMap(rp -> rp.getId(), rp -> rp, (rp1, rp2) -> rp1));
            }
            List<PurchaseRelatedProduct> updateRelatedProducts = new ArrayList<>();
            Map<Object, Object> userDeptMap = redisService.hmget(RedisKey.USER_GROUP_DEPT_TYPE);
            String detailId = "";

            List<PurchaseSpecialApplication> purchaseSpecialApplicationList = new ArrayList<>();
            List<PurchaseSpecialApplication> existPurchaseSpecialApplicationList = purchaseSpecialApplicationService.getByArrivalOrderId(purchaseArrivalOrder.getId());
            final Map<String, PurchaseSpecialApplication> existPurchaseSpecialApplicationMap = existPurchaseSpecialApplicationList.stream().collect(Collectors.toMap(PurchaseSpecialApplication::getItemId, e -> e));


            for (PurchaseArrivalProduct purchaseArrivalProduct : purchaseArrivalProducts) {
                if (purchaseArrivalProduct == null || purchaseArrivalProduct.getGoodProduct() == 0) continue;
                // 判断物品是否有 让步签收
                if (Constants.TWO_STR.equals(purchaseArrivalProduct.getConcessionAcceptance())) {
                    PurchaseSpecialApplication purchaseSpecialApp = existPurchaseSpecialApplicationMap.get(purchaseArrivalProduct.getItemId());
                    if (purchaseSpecialApp == null) {
                        PurchaseSpecialApplication purchaseSpecialApplication = new PurchaseSpecialApplication();
                        BeanUtils.copyProperties(purchaseArrivalProduct, purchaseSpecialApplication);
                        purchaseSpecialApplication.setProjectName(purchaseArrivalOrder.getProjectNumber());
                        purchaseSpecialApplication.setProjectNumber(purchaseArrivalOrder.getProjectNumber());
                        purchaseSpecialApplication.setInspector(purchaseArrivalOrder.getInspector());
                        purchaseSpecialApplication.setInspectorId(purchaseArrivalOrder.getInspectorId());
                        purchaseSpecialApplication.setArrivalOrderId(purchaseArrivalOrder.getId());
                        if (userDeptMap != null) {
                            purchaseSpecialApplication.setDepartmentId(userDeptMap.get(purchaseArrivalOrder.getApplicantId()) == null ?
                                    null : userDeptMap.get(purchaseArrivalOrder.getApplicantId()).toString());
                        }
                        purchaseSpecialApplication.setId(null);
                        purchaseSpecialApplicationList.add(purchaseSpecialApplication);
                    }
                }
                MaterialInventoryItem inventoryItem = new MaterialInventoryItem();
                BeanUtils.copyProperties(purchaseArrivalProduct, inventoryItem);
                inventoryItem.setId(null);
                if (itemInfoMap != null) {
                    MaterialManagement management = itemInfoMap.get(purchaseArrivalProduct.getItemId());
                    if (management != null) {
                        inventoryItem.setWarehouseName(management.getWarehouseName());
                        inventoryItem.setWarehouseCode(management.getWarehouseCode());
                        inventoryItems.add(inventoryItem);
                        purchaseArrivalProduct.setWarehouseCode(management.getWarehouseCode());
                        purchaseArrivalProduct.setWarehouseName(management.getWarehouseName());
                    }
                }

                if (relatedProductMap != null) {
                    int diff = purchaseArrivalProduct.getQuantity().intValue() - purchaseArrivalProduct.getGoodProduct();
                    if (diff > 0) {
                        PurchaseRelatedProduct relatedProduct = relatedProductMap.get(purchaseArrivalProduct.getOrderItemId());
                        detailId = relatedProduct.getDetailId();
                        if (relatedProduct != null) {
                            int newQuantity = relatedProduct.getQuantity().intValue() + diff;
                            relatedProduct.setQuantity((double) newQuantity);
                            updateRelatedProducts.add(relatedProduct);
                        }
                    }
                }

            }
            //保存让步签收
            if (CollectionUtils.isNotEmpty(purchaseSpecialApplicationList)) {
                purchaseSpecialApplicationService.saveBatch(purchaseSpecialApplicationList);
            }

            Map<String, String> inventoryIdMap = new HashMap<>();
            Map<String, String> inventoryNumberMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(inventoryItems)) {
                Map<String, List<MaterialInventoryItem>> inventoryMap = inventoryItems.stream().collect(Collectors.groupingBy(MaterialInventoryItem::getWarehouseCode));
                LocalDateTime now = LocalDateTime.now();
                inventoryMap.forEach((key, values) -> {
                    if (CollectionUtils.isNotEmpty(values)) {
                        MaterialInventoryItem inventoryItem = values.get(0);
                        String inNumber = getMaterialInNumber();
                        MaterialAllManagementInventory inventory = MaterialAllManagementInventory.builder()
                                .number(inNumber)
                                .handlerName(purchaseArrivalOrder.getArrivalConfirmUser())
                                .handlerId(purchaseArrivalOrder.getArrivalConfirmUserId())
                                .typeCode(CommonConstant.TEN_STR)
                                .inventoryCreationTime(now)
                                .contractNumber(purchaseArrivalOrder.getContractNumber())
                                .inspectorId(purchaseArrivalOrder.getInspectorId())
                                .arrivalPersonId(purchaseArrivalOrder.getArrivalConfirmUserId())
                                .purchaseArrivalNote(purchaseArrivalOrder.getPurchaseArrivalOrderNumber())
                                .productionDate(purchaseArrivalOrder.getProductionDate())
                                .orderNumber(purchaseArrivalOrder.getProjectNumber())
                                .preparerId(purchaseArrivalOrder.getArrivalConfirmUserId())
                                .supplierId(purchaseArrivalOrder.getSupplierId())
                                .supplierName(purchaseArrivalOrder.getSupplierName())
                                .warehouseCode(inventoryItem.getWarehouseCode())
                                .warehouseName(inventoryItem.getWarehouseName())
                                .purchaseOrder(purchaseArrivalOrder.getPurchaseOrderNumber())
                                .approveStatus(CommonConstant.ZERO_STR)
                                .build();
                        values.forEach(pii -> pii.setInventoryNumber(inventory.getNumber()));
                        materialApi.batchAdd(values);
                        ResultBody<String> inventoryRs = null;
                        switch (key) {
                            case PurchaseUseMaterialCode.YCLK_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_YCL_IN.getMsg());
                                inventoryRs = materialApi.addMaterialYCLLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.BPBJK_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_BPBJK_IN.getMsg());
                                inventoryRs = materialApi.addMaterialBHBJLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.YBYQK_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_YBYQK_IN.getMsg());
                                inventoryRs = materialApi.addMaterialYBYQLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.CLK_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_CLK_IN.getMsg());
                                inventoryRs = materialApi.addMaterialClLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.GJK_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_GJK_IN.getMsg());
                                inventoryRs = materialApi.addMaterialGJLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.LBYPK_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_LBYPK_IN.getMsg());
                                inventoryRs = materialApi.addMaterialLBYPLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.HXP_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_HXP_IN.getMsg());
                                inventoryRs = materialApi.addMaterialHXPLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.NYDL_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_NYDLK_IN.getMsg());
                                inventoryRs = materialApi.addMaterialNYDLLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.GJS_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_GJSK_IN.getMsg());
                                inventoryRs = materialApi.addMaterialGJSLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.DZSBK_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_DZSB_IN.getMsg());
                                inventoryRs = materialApi.addMaterialDZSBLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.ZPK_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_ZPK_IN.getMsg());
                                inventoryRs = materialApi.addMaterialZPKLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.BGJJ_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_BGJJ_IN.getMsg());
                                inventoryRs = materialApi.addMaterialBGJJLocationManagement(inventory);
                                break;
                            case PurchaseUseMaterialCode.FWK_CK:
                                inventory.setMenuId(PurchaseMenuIdCode.MENU_ID_FWK_IN.getMsg());
                                inventoryRs = materialApi.addMaterialFWKLocationManagement(inventory);
                                break;
                            default:
                                throw new ServiceException(PurchaseErrorCode.NOT_FIND_MATERIAL_CODE.getCode(), PurchaseErrorCode.NOT_FIND_MATERIAL_CODE.getMsg());
                        }

                        if (inventoryRs != null && StringUtils.isNotEmpty(inventoryRs.getData())) {
                            inventoryIdMap.put(key, inventoryRs.getData());
                            inventoryNumberMap.put(key, inNumber);
                        }
                    }
                });
            }

            for (PurchaseArrivalProduct purchaseArrivalProduct : purchaseArrivalProducts) {
                String id = inventoryIdMap.get(purchaseArrivalProduct.getWarehouseCode());
                String number = inventoryNumberMap.get(purchaseArrivalProduct.getWarehouseCode());
                if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(number)) {
                    purchaseArrivalProduct.setInventoryId(id);
                    purchaseArrivalProduct.setInventoryNumber(number);
                }
            }
            arrivalProductService.updateBatchById(purchaseArrivalProducts);

            if (CollectionUtils.isNotEmpty(updateRelatedProducts)) {
                relatedProductService.updateBatchById(updateRelatedProducts);
            }

            if (StringUtils.isNotBlank(detailId)) {
                orderDetailsMapper.updateOrderStatus(detailId);
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePurchase(String id) {
        baseMapper.deleteById(id);
        arrivalProductService.removeById(Wrappers.<PurchaseArrivalProduct>lambdaQuery().eq(PurchaseArrivalProduct::getSaleArrivalId, id));
    }

    /**
     * 生成到货单 创建流程 并且关联物品上传文件
     *
     * @param purchaseArrivalOrders
     */
    @Override
    @Transactional
    public void addPurchaseArrivalOrders(PurchaseArrivalOrders purchaseArrivalOrders) {
        baseMapper.insert(purchaseArrivalOrders);
        if (CollectionUtils.isNotEmpty(purchaseArrivalOrders.getPurchaseArrivalProducts())) {
            for (PurchaseArrivalProduct purchaseArrivalProduct : purchaseArrivalOrders.getPurchaseArrivalProducts()) {
                purchaseArrivalProduct.setSaleArrivalId(purchaseArrivalOrders.getId());
                arrivalProductService.save(purchaseArrivalProduct);
                if (CollectionUtils.isNotEmpty(purchaseArrivalProduct.getFileIds())) {
                    FileBusiness fileBusiness = new FileBusiness();
                    fileBusiness.setFileIds(purchaseArrivalProduct.getFileIds());
                    fileBusiness.setBusinessId(purchaseArrivalProduct.getId());
                    fileApi.updateBusinessById(fileBusiness);
                }
            }
        }
    }

    @Override
    public void addPurchaseBack(PurchaseReturns purchaseReturns) {
        purchaseReturnsMapper.insert(purchaseReturns);
        if (CollectionUtils.isNotEmpty(purchaseReturns.getPurchaseReturnGoodsList())) {
            for (PurchaseReturnGoods purchaseReturnGoods : purchaseReturns.getPurchaseReturnGoodsList()) {
                purchaseReturnGoods.setReturnId(purchaseReturns.getId());
                purchaseReturnGoodsMapper.insert(purchaseReturnGoods);
            }
        }
    }


    @Override
    public PurchaseArrivalOrders getPurchaseArrivalOrders(String id) {
        PurchaseArrivalOrders purchaseArrivalOrders = baseMapper.selectById(id);
        List<PurchaseArrivalProduct> purchaseArrivalProducts = arrivalProductService.list(Wrappers.<PurchaseArrivalProduct>lambdaQuery().eq(PurchaseArrivalProduct::getSaleArrivalId, id));

        if (CollectionUtils.isNotEmpty(purchaseArrivalProducts)) {
            for (PurchaseArrivalProduct purchaseArrivalProduct : purchaseArrivalProducts) {
                ResultBody<List<String>> fileIdsByBusinessId = fileApi.getFileIdsByBusinessId(purchaseArrivalProduct.getId());
                if (CollectionUtils.isNotEmpty(fileIdsByBusinessId.getData())) {
                    purchaseArrivalProduct.setFileIds(fileIdsByBusinessId.getData());
                }

            }
        }
        purchaseArrivalOrders.setPurchaseArrivalProducts(purchaseArrivalProducts);
        return purchaseArrivalOrders;
    }

    @Override
    public PurchaseArrivalOrders getReBackProduct(String id) {
        PurchaseArrivalOrders purchaseArrivalOrders = baseMapper.selectById(id);
        List<PurchaseArrivalProduct> purchaseArrivalProducts = arrivalProductService.list
                (Wrappers.<PurchaseArrivalProduct>lambdaQuery().eq(PurchaseArrivalProduct::getSaleArrivalId, id)
                        .ge(PurchaseArrivalProduct::getBadProduct, Constants.ZERO_STR)
                );
        if (CollectionUtils.isNotEmpty(purchaseArrivalProducts)) {
            for (PurchaseArrivalProduct purchaseArrivalProduct : purchaseArrivalProducts) {
                ResultBody<MaterialManagement> materialBYId = materialApi.getMaterialBYId(purchaseArrivalProduct.getItemId());
                MaterialManagement materialManagement = materialBYId.getData();
                purchaseArrivalProduct.setSpecificationModel(materialManagement.getSpecificationModel());
                purchaseArrivalProduct.setItemCode(materialManagement.getMaterialCode());
            }
            purchaseArrivalOrders.setPurchaseArrivalProducts(purchaseArrivalProducts);
        }
        return purchaseArrivalOrders;
    }

    @Override
    @RedissonLock(key = MATERIAL_PA_WAREHOUSE_NUMBER, prefixKey = "lock_")
    public String getArrivalOrderNumber() {

        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT_UN_SEPARATE));
        date = "PA".concat(date);
        String code = "";

        Serializable number = redisService.get(MATERIAL_PA_WAREHOUSE_NUMBER);
        if (number == null || StringUtils.isBlank(number.toString())) {
            ResultBody<String> resultBody = portalApi.getValueByCode(MATERIAL_PA_WAREHOUSE_NUMBER);
            if (resultBody != null && StringUtils.isNotBlank(resultBody.getData())) {
                number = resultBody.getData();
            }
        }
        if (number != null && StringUtils.isNotBlank(number.toString()) && number.toString().length() > 10) {
            String sequenceStr = number.toString().substring(10);
            int sequenceInt = Integer.parseInt(sequenceStr);
            sequenceInt = sequenceInt + 1;
            String newSequence = String.valueOf(sequenceInt);
            if (newSequence.length() == CommonConstant.FIVE_INT) {
                code = date.concat("0001");
            } else {
                code = date.concat(String.format("%04d", sequenceInt)); // 格式化数字为4位，不足部分用0填充
            }
        } else {
            code = date.concat("0001");
        }
        redisService.set(MATERIAL_PA_WAREHOUSE_NUMBER, code);
        DictInfo info = new DictInfo();
        info.setCsdm(MATERIAL_PA_WAREHOUSE_NUMBER);
        info.setCsmc(code);
        portalApi.updateValueByCode(info);
        return code;

//        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT_UN_SEPARATE));
//        date = "PA".concat(date);
//        String number = baseMapper.getArrivalOrderNumber();
//        if (StringUtils.isNotBlank(number) && number.length() > 10) {
//            String sequence = number.substring(10);
//            int sequenceInt = Integer.parseInt(sequence);
//            sequenceInt = sequenceInt + 1;
//            String newSequence = String.valueOf(sequenceInt);
//            if (newSequence.length() == CommonConstant.FIVE_INT) {
//                number = date.concat("0001");
//            } else {
//                if (newSequence.length() == CommonConstant.ONE_INT) {
//                    newSequence = "000".concat(newSequence);
//                } else if (newSequence.length() == CommonConstant.TWO_INT) {
//                    newSequence = "00".concat(newSequence);
//                } else if (newSequence.length() == CommonConstant.THREE_INT) {
//                    newSequence = "0".concat(newSequence);
//                }
//                number = date.concat(newSequence);
//            }
//        } else {
//            number = date.concat("0001");
//        }
//
//        return number;
    }

    @Override
    @RedissonLock(key = MATERIAL_IN_WAREHOUSE_NUMBER, prefixKey = "lock_")
    public String getMaterialInNumber() {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT_UN_SEPARATE));
        date = "IN".concat(date);
        String code = "";

        Serializable number = redisService.get(MATERIAL_IN_WAREHOUSE_NUMBER);
        if (number == null || StringUtils.isBlank(number.toString())) {
            ResultBody<String> resultBody = portalApi.getValueByCode(PURCHASE_IN_NUMBER);
            if (resultBody != null && StringUtils.isNotBlank(resultBody.getData())) {
                number = resultBody.getData();
            }
        }
        if (number != null && StringUtils.isNotBlank(number.toString()) && number.toString().length() > 10) {
            String sequenceStr = number.toString().substring(10);
            int sequenceInt = Integer.parseInt(sequenceStr);
            sequenceInt = sequenceInt + 1;
            String newSequence = String.valueOf(sequenceInt);
            if (newSequence.length() == CommonConstant.FIVE_INT) {
                code = date.concat("0001");
            } else {
                code = date.concat(String.format("%04d", sequenceInt)); // 格式化数字为4位，不足部分用0填充
            }
        } else {
            code = date.concat("0001");
        }
        redisService.set(MATERIAL_IN_WAREHOUSE_NUMBER, code);
        DictInfo info = new DictInfo();
        info.setCsdm(MATERIAL_IN_WAREHOUSE_NUMBER);
        info.setCsmc(code);
        portalApi.updateValueByCode(info);
        return code;
    }

    @Override
    public List<PurchaseArrivalOrders> getArrivalNumberList() {
        ResultBody<List<String>> resultBody = materialApi.getYCLIdList();
        if (CollectionUtils.isEmpty(resultBody.getData())) {
            return null;
        }
        List<String> yclIds = resultBody.getData();
        List<PurchaseArrivalProduct> purchaseArrivalProducts = arrivalProductService.
                list(Wrappers.<PurchaseArrivalProduct>lambdaQuery().in(PurchaseArrivalProduct::getItemId, yclIds).ne(PurchaseArrivalProduct::getUseStatus, Constants.ONE_STR));
        if (CollectionUtils.isNotEmpty(purchaseArrivalProducts)) {
            List<String> ids = purchaseArrivalProducts.stream().map(PurchaseArrivalProduct::getSaleArrivalId).distinct().collect(Collectors.toList());
            List<PurchaseArrivalOrders> purchaseArrivalOrders = baseMapper.selectList(Wrappers.<PurchaseArrivalOrders>lambdaQuery()
                    .select(PurchaseArrivalOrders::getId, PurchaseArrivalOrders::getPurchaseArrivalOrderNumber)
                    .in(PurchaseArrivalOrders::getId, ids));
            return purchaseArrivalOrders;
        }
        return null;
    }

    /**
     * 获取入库完成的订单号
     *
     * @return
     */
    @Override
    public List<PurchaseArrivalOrders> getOrderNumberList() {
        List<PurchaseArrivalOrders> newArrList = new ArrayList<>();
        List<PurchaseArrivalOrders> purchaseArrivalOrders = baseMapper.selectList(Wrappers.<PurchaseArrivalOrders>lambdaQuery().select(PurchaseArrivalOrders::getId, PurchaseArrivalOrders::getPurchaseOrderNumber, PurchaseArrivalOrders::getSupplierName,
                PurchaseArrivalOrders::getSupplierId).eq(PurchaseArrivalOrders::getStatus, Constants.THREE_STR)
                .in(PurchaseArrivalOrders::getCheckStatus, Constants.ONE_STR, Constants.TWO_STR)
        );
        List<String> collect = purchaseArrivalOrders.stream().map(PurchaseArrivalOrders::getPurchaseOrderNumber).distinct().collect(Collectors.toList());
        for (String orderNumber : collect) {
            PurchaseArrivalOrders purchaseArrivalOrders1 = new PurchaseArrivalOrders();
            purchaseArrivalOrders1.setPurchaseOrderNumber(orderNumber);
            purchaseArrivalOrders1.setId(orderNumber);
            newArrList.add(purchaseArrivalOrders1);
        }
        return newArrList;
    }

    @Override
    public List<PurchaseArrivalOrders> getSuppilerListByNumber(String number) {
        List<PurchaseArrivalOrders> purchaseArrivalOrders = baseMapper.selectList(Wrappers.<PurchaseArrivalOrders>lambdaQuery().select(PurchaseArrivalOrders::getSupplierName,
                PurchaseArrivalOrders::getSupplierId).eq(PurchaseArrivalOrders::getPurchaseOrderNumber, number).eq(PurchaseArrivalOrders::getStatus, Constants.THREE_STR)
                .in(PurchaseArrivalOrders::getCheckStatus, Constants.ONE_STR, Constants.TWO_STR)
        );
        List<PurchaseArrivalOrders> collect = purchaseArrivalOrders.stream()
                .collect(Collectors.toMap(
                        po -> Arrays.asList(po.getSupplierName(), po.getSupplierId()), // 使用supplierName和supplierId作为key
                        Function.identity(), // value就是PurchaseArrivalOrders对象本身
                        (existing, replacement) -> existing, // 如果遇到重复，保留第一个
                        LinkedHashMap::new // 使用LinkedHashMap保持插入顺序
                )).values().stream() // 转换为values的stream
                .collect(Collectors.toList());// 收集为List
        return collect;
    }

    @Override
    public List<PurchaseArrivalProduct> getOrderItemListById(String number) {
        List<PurchaseArrivalOrders> purchaseArrivalOrders = baseMapper.selectList(Wrappers.<PurchaseArrivalOrders>lambdaQuery().select(PurchaseArrivalOrders::getId,
                PurchaseArrivalOrders::getSupplierId).eq(PurchaseArrivalOrders::getPurchaseOrderNumber, number).eq(PurchaseArrivalOrders::getStatus, Constants.THREE_STR)
                .in(PurchaseArrivalOrders::getCheckStatus, Constants.ONE_STR, Constants.TWO_STR)
        );
        List<String> collect = purchaseArrivalOrders.stream().map(PurchaseArrivalOrders::getId).distinct().collect(Collectors.toList());
        List<PurchaseArrivalProduct> list = arrivalProductService.getSelectPurchaseArrivalProductList(collect);
        return list;
    }

    @Override
    public PurchaseArrivalProduct getProductInfoByNumberAndCode(PurchaseArrivalOrders purchaseArrivalOrders) {
        List<PurchaseArrivalOrders> purchaseArrivalOrderList = baseMapper.selectList(Wrappers.<PurchaseArrivalOrders>lambdaQuery().select(PurchaseArrivalOrders::getId,
                PurchaseArrivalOrders::getSupplierId).eq(PurchaseArrivalOrders::getPurchaseOrderNumber, purchaseArrivalOrders.getPurchaseOrderNumber()).eq(PurchaseArrivalOrders::getStatus, Constants.THREE_STR)
                .in(PurchaseArrivalOrders::getCheckStatus, Constants.ONE_STR, Constants.TWO_STR)
        );
        if (CollectionUtils.isEmpty(purchaseArrivalOrderList)){
            return null;
        }
        List<String> collect = purchaseArrivalOrderList.stream().map(PurchaseArrivalOrders::getId).distinct().collect(Collectors.toList());
        List<PurchaseArrivalProduct> selectPurchaseArrivalProductAndCodeList = arrivalProductService.getSelectPurchaseArrivalProductAndCodeList(collect, purchaseArrivalOrders.getItemCode());
        for (PurchaseArrivalProduct purchaseArrivalProduct : selectPurchaseArrivalProductAndCodeList) {
            if (purchaseArrivalProduct.getForzenQuantity() != null && purchaseArrivalProduct.getGoodProduct() != null) {
                if (purchaseArrivalProduct.getGoodProduct().compareTo(purchaseArrivalProduct.getForzenQuantity()) <= 0) {
                    purchaseArrivalProduct.setGoodProduct(0);
                } else {
                    Integer count = purchaseArrivalProduct.getGoodProduct() - purchaseArrivalProduct.getForzenQuantity();
                    purchaseArrivalProduct.setGoodProduct(count);
                }

            }
        }
        if (CollectionUtils.isEmpty(selectPurchaseArrivalProductAndCodeList)) {
            return null;
        }
        return selectPurchaseArrivalProductAndCodeList.get(0);
    }

    @Override
    public List<PurchaseArrivalProduct>  getBrocadeByNumberAndCode(PurchaseArrivalOrders purchaseArrivalOrders) {
        List<PurchaseArrivalOrders> purchaseArrivalOrderList = baseMapper.selectList(Wrappers.<PurchaseArrivalOrders>lambdaQuery().select(PurchaseArrivalOrders::getId,
                PurchaseArrivalOrders::getSupplierId).eq(PurchaseArrivalOrders::getPurchaseOrderNumber, purchaseArrivalOrders.getPurchaseOrderNumber()).eq(PurchaseArrivalOrders::getStatus, Constants.THREE_STR)
                .in(PurchaseArrivalOrders::getCheckStatus, Constants.ONE_STR, Constants.TWO_STR)
        );
        List<String> collect = purchaseArrivalOrderList.stream().map(PurchaseArrivalOrders::getId).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            return null;
        }
        List<PurchaseArrivalProduct> list = arrivalProductService.list(Wrappers.<PurchaseArrivalProduct>lambdaQuery().in(PurchaseArrivalProduct::getSaleArrivalId, collect));
        List<String> inventoryList = list.stream().map(PurchaseArrivalProduct::getInventoryNumber).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(inventoryList)) {
            return null;
        }
        List<PurchaseArrivalProduct> brocadeByNumberAndCode = arrivalProductService.getBrocadeByNumberAndCode(inventoryList, purchaseArrivalOrders.getItemCode());
        return brocadeByNumberAndCode;
    }
    @Override
    public List<PurchaseArrivalProduct>  getBatchNumberByNumberAndCode(PurchaseArrivalOrders purchaseArrivalOrders) {
        List<PurchaseArrivalProduct> brocadeByNumberAndCode = arrivalProductService.getBatchNumberByNumberAndCode(purchaseArrivalOrders.getBarcodeNumber(), purchaseArrivalOrders.getItemCode());
        return brocadeByNumberAndCode;
    }

    @Override
    public List<PurchaseArrivalProduct> getBatchNumber(String id) {
        PurchaseArrivalOrders purchaseArrivalOrders = baseMapper.selectById(id);
        List<PurchaseArrivalProduct> purchaseArrivalProducts = arrivalProductService.
                list(Wrappers.<PurchaseArrivalProduct>lambdaQuery().select(PurchaseArrivalProduct::getId, PurchaseArrivalProduct::getPcNumber).eq(PurchaseArrivalProduct::getSaleArrivalId
                        , id).ne(PurchaseArrivalProduct::getUseStatus, Constants.ONE_STR));
        for (PurchaseArrivalProduct purchaseArrivalProduct : purchaseArrivalProducts) {
            purchaseArrivalProduct.setSupplierId(purchaseArrivalOrders.getSupplierId());
            purchaseArrivalProduct.setSupplierName(purchaseArrivalOrders.getSupplierName());
            purchaseArrivalProduct.setArrivalTime(purchaseArrivalOrders.getCreateTime());
        }
        return purchaseArrivalProducts;
    }

    @Override
    public PurchaseArrivalOrders getCheckDetail(String id) {
        PurchaseArrivalOrders purchaseArrivalOrders = baseMapper.selectById(id);
        List<PurchaseArrivalProduct> products = arrivalProductService.list(Wrappers.<PurchaseArrivalProduct>lambdaQuery().eq(PurchaseArrivalProduct::getSaleArrivalId, id));

        if (CollectionUtils.isNotEmpty(products)) {
            ResultBody<List<FileBusiness>> resultBody = fileApi.getFileBusinessByIds(products.stream().map(p -> p.getId()).collect(Collectors.toList()));
            Map<String, FileBusiness> fileBusinessMap = null;
            if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
                fileBusinessMap = resultBody.getData().stream().collect(Collectors.toMap(fb -> fb.getBusinessId(), fb -> fb, (fb1, fb2) -> fb1));
            }
            List<PurchaseArrivalProduct> newProducts = new ArrayList<>();
            for (PurchaseArrivalProduct arrivalProduct : products) {
                if (CommonConstant.ZERO_STR.equals(arrivalProduct.getApproveStatus())
                        || CommonConstant.FOUR_STR.equals(arrivalProduct.getApproveStatus())) {
                    newProducts.add(arrivalProduct);
                }
                if (fileBusinessMap != null) {
                    FileBusiness fileBusiness = fileBusinessMap.get(arrivalProduct.getId());
                    if (fileBusiness != null) {
                        arrivalProduct.setFileIds(fileBusiness.getFileIds());
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(newProducts)) {
                List<String> orderItemIds = newProducts.stream().map(np -> np.getOrderItemId()).collect(Collectors.toList());
                Map<String, Double> relatedProductMap = null;
                if (CollectionUtils.isNotEmpty(orderItemIds)) {
                    List<PurchaseRelatedProduct> relatedProducts = relatedProductService.list(Wrappers.<PurchaseRelatedProduct>lambdaQuery().in(PurchaseRelatedProduct::getId, orderItemIds));
                    relatedProductMap = relatedProducts.stream().collect(Collectors.toMap(rp -> rp.getId(), rp -> rp.getQuantity(), (rp1, rp2) -> rp1));
                }

                if (relatedProductMap != null) {
                    for (PurchaseArrivalProduct purchaseArrivalProduct : newProducts) {
                        purchaseArrivalProduct.setSurplusQuantity(relatedProductMap.get(purchaseArrivalProduct.getOrderItemId()));
                    }
                }
                purchaseArrivalOrders.setPurchaseArrivalProducts(newProducts);
            }
        }

        return purchaseArrivalOrders;
    }
}
